import bluetoothManager from '../../utils/bluetooth.js'

Page({
  data: {
    isConnected: false,
    deviceInfo: {},
    connectionTime: '',
    services: [],
    connectionHistory: []
  },

  onLoad() {
    this.checkConnectionStatus()
    this.loadConnectionHistory()
    this.setupConnectionListener()
  },

  onShow() {
    this.checkConnectionStatus()
  },

  // 检查连接状态
  checkConnectionStatus() {
    const isConnected = bluetoothManager.isConnected
    this.setData({
      isConnected: isConnected
    })

    if (isConnected) {
      this.getDeviceInfo()
      this.getServices()
    } else {
      // 如果没有连接，尝试从存储中获取设备信息
      const deviceInfo = wx.getStorageSync('connectedDeviceInfo')
      if (deviceInfo) {
        this.setData({
          deviceInfo: deviceInfo
        })
      }
    }
  },

  // 设置连接状态监听
  setupConnectionListener() {
    bluetoothManager.setOnConnectionStateChange((connected) => {
      this.setData({
        isConnected: connected
      })

      if (connected) {
        this.getDeviceInfo()
        this.getServices()
        this.updateConnectionTime()
      } else {
        this.setData({
          deviceInfo: {},
          services: []
        })
      }
    })
  },

  // 连接设备
  async connectToDevice() {
    wx.showLoading({
      title: '连接中...'
    })

    try {
      // 从存储中获取设备信息
      const lastDeviceId = wx.getStorageSync('lastConnectedDevice')
      const deviceInfo = wx.getStorageSync('connectedDeviceInfo')
      
      if (lastDeviceId) {
        const connectResult = await bluetoothManager.connectDevice(lastDeviceId, deviceInfo?.name)
        this.addConnectionHistory(deviceInfo?.name || '上次连接的设备', true)
        
        // 更新连接时间
        this.updateConnectionTime()
      } else {
        wx.hideLoading()
        wx.showToast({
          title: '请先扫描并连接设备',
          icon: 'none'
        })
      }
    } catch (error) {
      wx.hideLoading()
      console.error('连接失败:', error)
      this.addConnectionHistory('未知设备', false)
      
      // 根据错误类型显示不同的提示
      if (error.errMsg && error.errMsg.includes('already connect')) {
        wx.showToast({
          title: '设备已连接',
          icon: 'none',
          duration: 2000
        })
      } else {
        wx.showToast({
          title: '连接失败',
          icon: 'none'
        })
      }
    }
  },

  // 断开连接
  async disconnectDevice() {
    try {
      await bluetoothManager.disconnect()
      wx.showToast({
        title: '已断开连接',
        icon: 'success'
      })
    } catch (error) {
      console.error('断开连接失败:', error)
      wx.showToast({
        title: '断开连接失败',
        icon: 'none'
      })
    }
  },

  // 获取设备信息
  async getDeviceInfo() {
    try {
      // 这里应该从蓝牙管理器获取设备信息
      const deviceInfo = {
        name: 'GAIA Device',
        deviceId: bluetoothManager.deviceId || 'Unknown'
      }
      
      this.setData({
        deviceInfo: deviceInfo
      })
    } catch (error) {
      console.error('获取设备信息失败:', error)
    }
  },

  // 获取服务信息
  async getServices() {
    if (!bluetoothManager.deviceId) return

    try {
      const services = await bluetoothManager.getServices(bluetoothManager.deviceId)
      
      // 获取每个服务的特征值
      const servicesWithCharacteristics = []
      for (const service of services) {
        const characteristics = await bluetoothManager.getCharacteristics(
          bluetoothManager.deviceId, 
          service.uuid
        )
        servicesWithCharacteristics.push({
          ...service,
          characteristics: characteristics
        })
      }
      
      this.setData({
        services: servicesWithCharacteristics
      })
    } catch (error) {
      console.error('获取服务信息失败:', error)
    }
  },

  // 更新连接时间
  updateConnectionTime() {
    const now = new Date()
    const timeString = now.toLocaleString('zh-CN')
    this.setData({
      connectionTime: timeString
    })
  },

  // 添加连接历史
  addConnectionHistory(deviceName, success) {
    const history = this.data.connectionHistory
    const newRecord = {
      deviceName: deviceName,
      time: new Date().toLocaleString('zh-CN'),
      success: success
    }
    
    history.unshift(newRecord)
    
    // 只保留最近10条记录
    if (history.length > 10) {
      history.pop()
    }
    
    this.setData({
      connectionHistory: history
    })
    
    // 保存到本地存储
    wx.setStorageSync('connectionHistory', history)
  },

  // 加载连接历史
  loadConnectionHistory() {
    try {
      const history = wx.getStorageSync('connectionHistory') || []
      this.setData({
        connectionHistory: history
      })
    } catch (error) {
      console.error('加载连接历史失败:', error)
    }
  },

  // 导航到设备控制页面
  navigateToDevice() {
    wx.switchTab({
      url: '/pages/information/information'
    })
  },

  // 导航到设置页面
  navigateToSettings() {
    wx.switchTab({
      url: '/pages/settings/settings'
    })
  },

  // 获取设备信息
  getDeviceInfo() {
    if (bluetoothManager.isConnected && bluetoothManager.deviceId) {
      // 如果已连接，从蓝牙管理器获取设备信息
      const deviceInfo = {
        deviceId: bluetoothManager.deviceId,
        name: bluetoothManager.deviceName || '未知设备'
      }
      this.setData({
        deviceInfo: deviceInfo
      })
    } else {
      // 从存储中获取设备信息
      const deviceInfo = wx.getStorageSync('connectedDeviceInfo')
      if (deviceInfo) {
        this.setData({
          deviceInfo: deviceInfo
        })
      }
    }
  }
})
